package com.thghh.bcode.compiler;

import javax.tools.SimpleJavaFileObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;

/**
 * @author Zhikang.Peng
 * @version 1.0
 * @email thghh@qq.com
 * @date 2020/12/4 16:51
 */
public class ByteCodeJavaFileObject extends SimpleJavaFileObject {

    private ByteArrayOutputStream outputStream;
    private String className;

    /**
     * Construct a SimpleJavaFileObject of the given kind and with the
     * given class name.
     *
     * @param className class name
     * @param kind      the kind of this file object
     */
    protected ByteCodeJavaFileObject(String className, Kind kind) {
        super(URI.create("memory:///" + className.replaceAll("\\.", "/") + kind.extension), kind);
        this.className = className;
        this.outputStream = new ByteArrayOutputStream(512);
    }

    @Override
    public OutputStream openOutputStream() throws IOException {
        return this.outputStream;
    }

    /**
     * FileManager会使用该方法获取编译后的byte，然后将类加载到JVM
     */
    public byte[] getBytes() {
        return this.outputStream.toByteArray();
    }

    public String getClassName() {
        return className;
    }
}
